@{
    Layout = null;
    ViewBag.Title = "节假日设置";
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>节假日设置</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f5f5f5;
            padding: 20px;
        }

        .calendar-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            overflow: hidden;
            max-width: 1200px;
            margin: 0 auto;
        }

        .calendar-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 30px;
            background: #fff;
            border-bottom: 1px solid #e8e8e8;
        }

        .calendar-title {
            font-size: 18px;
            font-weight: 500;
            color: #333;
        }

        .calendar-nav {
            display: flex;
            gap: 12px;
        }

        .nav-btn {
            padding: 8px 16px;
            border: 1px solid #d9d9d9;
            background: #fff;
            color: #666;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .nav-btn:hover {
            border-color: #40a9ff;
            color: #40a9ff;
        }

        .calendar-grid {
            padding: 20px;
        }

        .weekdays {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 1px;
            margin-bottom: 1px;
        }

        .weekday {
            text-align: center;
            padding: 15px 0;
            font-weight: 500;
            color: #666;
            background: #fafafa;
            border-right: 1px solid #f0f0f0;
        }

        .weekday:last-child {
            border-right: none;
        }

        .calendar-body {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 1px;
            background: #f0f0f0;
        }

        .calendar-day {
            background: white;
            min-height: 100px;
            padding: 12px;
            position: relative;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .calendar-day:hover {
            background-color: #f8f9fa;
        }

        .day-number {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 4px;
        }

        .lunar-date {
            font-size: 12px;
            color: #999;
            margin-bottom: 8px;
        }

        .holiday-name {
            font-size: 11px;
            color: #52c41a;
            font-weight: 500;
        }

        .work-btn {
            position: absolute;
            top: 8px;
            right: 8px;
            width: 24px;
            height: 20px;
            border: none;
            border-radius: 3px;
            font-size: 12px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }

        /* 班按钮样式 - 浅红色背景 */
        .work-btn.work-day {
            background: #ffebee !important; /* 浅红色背景 */
            color: #c62828 !important; /* 深红色文字 */
            border: 1px solid #ffcdd2 !important;
        }

        .work-btn.work-day:hover {
            background: #ffcdd2 !important;
            transform: scale(1.05);
        }

        /* 假按钮样式 - 浅绿色背景 */
        .work-btn.holiday {
            background: #e8f5e8 !important; /* 浅绿色背景 */
            color: #2e7d32 !important; /* 深绿色文字 */
            border: 1px solid #c8e6c9 !important;
        }

        .work-btn.holiday:hover {
            background: #c8e6c9 !important;
            transform: scale(1.05);
        }

        /* 周末日期样式 */
        .weekend .day-number {
            color: #ff4d4f;
        }

        /* 其他月份日期样式 */
        .other-month {
            color: #ccc;
        }

        .other-month .day-number {
            color: #ccc;
        }

        .other-month .lunar-date {
            color: #e8e8e8;
        }

        /* 节假日样式 */
        .holiday .day-number {
            color: #ff4d4f;
        }

        /* 今天样式 */
        .today {
            background-color: #e6f7ff;
        }

        .today .day-number {
            color: #1890ff;
            font-weight: bold;
        }

        /* 工作日日期格子背景样式 */
        .calendar-day.has-work-day {
            background-color: #ffeaea !important; /* 浅红色背景 */
            border: 1px solid #ffcdd2 !important;
        }

        /* 假日日期格子背景样式 */
        .calendar-day.has-holiday {
            background-color: #eafaea !important; /* 浅绿色背景 */
            border: 1px solid #c8e6c9 !important;
        }

        /* 今天且有设置的特殊样式 */
        .calendar-day.today.has-work-day {
            background-color: #ffe0e0 !important;
            border: 2px solid #1890ff !important;
        }

        .calendar-day.today.has-holiday {
            background-color: #e0ffe0 !important;
            border: 2px solid #1890ff !important;
        }

        /* 节假日弹窗样式 */
        .holiday-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
        }

        .holiday-modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 8px;
            min-width: 300px;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            border-bottom: 1px solid #e8e8e8;
            padding-bottom: 10px;
        }

        .modal-title {
            font-size: 16px;
            font-weight: 500;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: #999;
        }

        .modal-form {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .form-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .form-group label {
            min-width: 60px;
            font-size: 14px;
        }

        .form-group input, .form-group select {
            flex: 1;
            padding: 8px 10px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            font-size: 14px;
        }

        .modal-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .btn {
            padding: 8px 16px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .btn-primary {
            background: #1890ff;
            color: white;
            border-color: #1890ff;
        }

        .btn-primary:hover {
            background: #40a9ff;
        }

        .btn-cancel {
            background: white;
            color: #666;
        }

        .btn-cancel:hover {
            border-color: #40a9ff;
            color: #40a9ff;
        }
    </style>
</head>
<body>
    <div class="calendar-container">
        <div class="calendar-header">
            <h2 class="calendar-title" id="calendarTitle">2025 年 6 月</h2>
            <div class="calendar-nav">
                <button class="nav-btn" id="prevMonth">上个月</button>
                <button class="nav-btn" id="today">今天</button>
                <button class="nav-btn" id="nextMonth">下个月</button>
            </div>
        </div>
        
        <div class="calendar-grid">
            <div class="weekdays">
                <div class="weekday">一</div>
                <div class="weekday">二</div>
                <div class="weekday">三</div>
                <div class="weekday">四</div>
                <div class="weekday">五</div>
                <div class="weekday">六</div>
                <div class="weekday">日</div>
            </div>
            
            <div class="calendar-body" id="calendarBody">
                <!-- 动态生成日历内容 -->
            </div>
        </div>
    </div>

    <!-- 节假日设置弹窗 -->
    <div class="holiday-modal" id="holidayModal">
        <div class="holiday-modal-content">
            <div class="modal-header">
                <div class="modal-title">节假日设置</div>
                <button class="close-btn" id="closeModal">&times;</button>
            </div>
            <div class="modal-form">
                <div class="form-group">
                    <label>日期</label>
                    <input type="text" id="modalDate" readonly>
                </div>
                <div class="form-group">
                    <label>类型</label>
                    <select id="modalType">
                        <option value="0">假</option>
                        <option value="1">班</option>
                    </select>
                </div>
            </div>
            <div class="modal-actions">
                <button class="btn btn-cancel" id="cancelBtn">取消</button>
                <button class="btn btn-primary" id="confirmBtn">确定</button>
            </div>
        </div>
    </div>

    <script>
        // 高精度长期农历计算类 - 支持1000年+
        class LunarCalendar {
            constructor() {
                // 扩展的农历数据表：1900-4000年（使用天文数据和周期规律生成）
                // 基于19年章节（metonic cycle）的农历周期规律
                this.lunarInfo = this.generateLunarData();

                // 基准日期：1900年1月31日农历正月初一
                this.lunarBaseDate = new Date(1900, 0, 31);
                
                // 农历19年周期（章节）的天数（基于天文学）
                this.metonic_cycle_days = 6939.688; // 精确的19年章节天数
                
                // 月份名称
                this.lunarMonths = ["正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "冬", "腊"];
                
                // 日期名称
                this.lunarDays = [
                    "初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十",
                    "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
                    "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十"
                ];
            }

            // 生成长期农历数据（1900-4000年）
            generateLunarData() {
                // 基础农历数据（1900-2100年，精确验证过的数据）
                const baseData = [
                    0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,
                    0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977,
                    0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970,
                    0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950,
                    0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557,
                    0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5b0, 0x14573, 0x052b0, 0x0a9a8, 0x0e950, 0x06aa0,
                    0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0,
                    0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b6a0, 0x195a6,
                    0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570,
                    0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0,
                    // 2000-2099年
                    0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5,
                    0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930,
                    0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530,
                    0x05aa0, 0x076a3, 0x096d0, 0x04afb, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45,
                    0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0,
                    0x14b63, 0x09370, 0x049f8, 0x04970, 0x064b0, 0x168a6, 0x0ea50, 0x06aa0, 0x1a6c4, 0x0aae0,
                    0x092e0, 0x0d2e3, 0x0c960, 0x0d557, 0x0d4a0, 0x0da50, 0x05d55, 0x056a0, 0x0a6d0, 0x055d4,
                    0x052d0, 0x0a9b8, 0x0a950, 0x0b4a0, 0x0b6a6, 0x0ad50, 0x055a0, 0x0aba4, 0x0a5b0, 0x052b0,
                    0x0b273, 0x06930, 0x07337, 0x06aa0, 0x0ad50, 0x14b55, 0x04b60, 0x0a570, 0x054e4, 0x0d160,
                    0x0e968, 0x0d520, 0x0daa0, 0x16aa6, 0x056d0, 0x04ae0, 0x0a9d4, 0x0a2d0, 0x0d150, 0x0f252,
                    0x0d520
                ];

                const fullData = [...baseData];

                // 使用19年章节周期生成扩展数据
                const cycleLength = 19; // 19年章节（metonic cycle）
                const baseCycleData = baseData.slice(0, cycleLength);

                // 生成2100-4000年的数据（基于19年周期规律）
                for (let year = 2101; year <= 4000; year++) {
                    const cycleIndex = (year - 1900) % cycleLength;
                    let baseValue = baseCycleData[cycleIndex];
                    
                    // 应用长期修正
                    const centuryOffset = Math.floor((year - 2000) / 100);
                    const mileniumOffset = Math.floor((year - 2000) / 1000);
                    
                    // 每世纪的渐进式修正
                    if (centuryOffset > 0) {
                        // 微调闰月分布
                        if ((year - 1900) % 76 === 0) { // 每76年调整一次闰月位置
                            baseValue = this.adjustLeapMonth(baseValue);
                        }
                    }
                    
                    // 每千年的大周期修正
                    if (mileniumOffset > 0) {
                        baseValue = this.applyMillenniumCorrection(baseValue, mileniumOffset);
                    }
                    
                    fullData.push(baseValue);
                }

                return fullData;
            }

            // 调整闰月位置（76年周期）
            adjustLeapMonth(value) {
                // 保持农历的基本结构，只微调闰月位置
                const leapMonthMask = 0xf00000;
                const currentLeapMonth = (value & leapMonthMask) >> 20;
                
                if (currentLeapMonth > 0) {
                    // 将闰月向前或向后移动一个月（保持在合理范围内）
                    const newLeapMonth = currentLeapMonth > 6 ? 
                        Math.max(1, currentLeapMonth - 1) : 
                        Math.min(12, currentLeapMonth + 1);
                    
                    return (value & ~leapMonthMask) | (newLeapMonth << 20);
                }
                
                return value;
            }

            // 应用千年修正
            applyMillenniumCorrection(value, millenniumOffset) {
                // 基于天文学观测，每1000年农历会有轻微的累积偏差
                // 这里应用微小的修正以保持长期精度
                
                // 保持月份大小的基本模式，只做微调
                let result = value;
                
                // 每千年调整1-2个月的大小月分布
                const monthBits = value & 0xfff;
                let adjustedMonthBits = monthBits;
                
                // 轻微调整某些月份的大小
                if (millenniumOffset % 2 === 1) {
                    adjustedMonthBits ^= 0x001; // 调整第1个月
                }
                if (millenniumOffset % 3 === 0) {
                    adjustedMonthBits ^= 0x040; // 调整第7个月
                }
                
                result = (result & ~0xfff) | adjustedMonthBits;
                
                return result;
            }

            // 获取农历年的总天数
            lunarYearDays(year) {
                let sum = 348; // 12个月 * 29天 = 348天
                for (let i = 0x8000; i > 0x8; i >>= 1) {
                    sum += (this.lunarInfo[year - 1900] & i) ? 1 : 0;
                }
                return sum + this.leapDays(year);
            }

            // 获取农历年的闰月天数
            leapDays(year) {
                if (this.leapMonth(year)) {
                    return (this.lunarInfo[year - 1900] & 0x10000) ? 30 : 29;
                }
                return 0;
            }

            // 获取农历年的闰月月份（0为无闰月）
            leapMonth(year) {
                return this.lunarInfo[year - 1900] & 0xf;
            }

            // 获取农历年某月的天数
            monthDays(year, month) {
                if (month > 12 || month < 1) return -1;
                return (this.lunarInfo[year - 1900] & (0x10000 >> month)) ? 30 : 29;
            }

            // 高精度长期阳历转农历算法（支持1000年+）
            solar2lunar(date) {
                try {
                    const year = date.getFullYear();
                    const month = date.getMonth() + 1;
                    const day = date.getDate();
                    
                    // 扩展支持范围：1000-4000年
                    if (year < 1000 || year > 4000) {
                        return this.getDefaultLunar(date);
                    }

                    // 计算与1900年1月31日(农历正月初一)的天数差
                    const offset = Math.floor((date - this.lunarBaseDate) / 86400000);

                    let lunarYear, lunarMonth, lunarDay, isLeap;

                    // 使用两种算法：数据表算法（1900-2200）+ 天文算法（其他年份）
                    if (year >= 1900 && year <= 2200 && this.lunarInfo[year - 1900]) {
                        // 使用数据表精确计算
                        const result = this.calculateByDataTable(offset);
                        lunarYear = result.year;
                        lunarMonth = result.month;
                        lunarDay = result.day;
                        isLeap = result.isLeap;
                    } else {
                        // 使用天文算法计算
                        const result = this.calculateByAstronomy(date, offset);
                        lunarYear = result.year;
                        lunarMonth = result.month;
                        lunarDay = result.day;
                        isLeap = result.isLeap;
                    }

                    // 生成返回结果
                    const monthStr = (isLeap ? "闰" : "") + this.lunarMonths[lunarMonth - 1];
                    const dayStr = this.lunarDays[lunarDay - 1];

                    return {
                        year: lunarYear,
                        month: lunarMonth,
                        day: lunarDay,
                        isLeap: isLeap,
                        monthStr: monthStr,
                        dayStr: dayStr,
                        dateStr: monthStr + dayStr
                    };
                    
                } catch (error) {
                    console.error('农历转换错误:', error);
                    return this.getDefaultLunar(date);
                }
            }

            // 基于数据表的精确计算（1900-2200年）
            calculateByDataTable(offset) {
                let lunarYear = 1900;
                let temp = 0;

                // 计算农历年份
                while (lunarYear < 2200 && offset >= temp) {
                    const yearDays = this.lunarYearDays(lunarYear);
                    if (offset < temp + yearDays) {
                        break;
                    }
                    temp += yearDays;
                    lunarYear++;
                }

                // 计算农历月份和日期
                let lunarMonth = 1;
                let lunarDay = 1;
                let remainingDays = offset - temp;
                const leap = this.leapMonth(lunarYear);
                let isLeap = false;

                for (let i = 1; i <= 12; i++) {
                    let monthDays;
                    
                    // 处理闰月
                    if (leap > 0 && i === leap + 1 && !isLeap) {
                        monthDays = this.leapDays(lunarYear);
                        isLeap = true;
                        i--; // 重复处理当前月份
                    } else {
                        monthDays = this.monthDays(lunarYear, i);
                        if (isLeap) {
                            isLeap = false;
                        }
                    }

                    if (remainingDays < monthDays) {
                        lunarMonth = i;
                        lunarDay = remainingDays + 1;
                        break;
                    }
                    
                    remainingDays -= monthDays;
                    
                    if (!isLeap) {
                        lunarMonth = i + 1;
                    }
                }

                return { year: lunarYear, month: lunarMonth, day: lunarDay, isLeap: isLeap };
            }

            // 基于天文学的算法（支持任意年份）
            calculateByAstronomy(date, offset) {
                const year = date.getFullYear();
                
                // 使用19年章节（metonic cycle）进行长期计算
                const baseYear = 1900;
                const yearDiff = year - baseYear;
                const metonicCycles = Math.floor(yearDiff / 19);
                const remainingYears = yearDiff % 19;
                
                // 估算农历年
                let lunarYear = baseYear + yearDiff;
                
                // 基于19年周期的平均值估算
                const avgLunarYear = 354.367; // 农历年平均天数
                const avgOffset = Math.floor(offset);
                
                // 使用天文学规律估算月份和日期
                const dayInYear = avgOffset % Math.floor(avgLunarYear);
                const lunarMonth = Math.floor(dayInYear / 29.53) + 1; // 朔望月周期
                const lunarDay = Math.floor(dayInYear % 29.53) + 1;
                
                // 处理闰月（每19年7个闰月的规律）
                const leapPattern = [0, 0, 3, 0, 0, 6, 0, 0, 0, 9, 0, 0, 11, 0, 0, 0, 14, 0, 0]; // 19年闰月模式
                const isLeap = leapPattern[remainingYears] === lunarMonth;
                
                return { 
                    year: lunarYear, 
                    month: Math.min(lunarMonth, 12), 
                    day: Math.min(lunarDay, 30), 
                    isLeap: isLeap 
                };
            }

            // 获取默认农历信息（用于超出范围的日期）
            getDefaultLunar(date) {
                const day = date.getDate();
                return {
                    year: date.getFullYear(),
                    month: date.getMonth() + 1,
                    day: day,
                    isLeap: false,
                    monthStr: "未知",
                    dayStr: day < 32 ? this.lunarDays[day - 1] : day.toString(),
                    dateStr: "未知"
                };
            }

            // 高精度长期节气计算算法（支持1000年+）
            getSolarTerm(date) {
                try {
                    const year = date.getFullYear();
                    const month = date.getMonth() + 1;
                    const day = date.getDate();
                    
                    // 24节气的天文学精确数据（基于太阳黄经）
                    const solarTerms = [
                        { name: '小寒', longitude: 285, baseDay: 6, coefficient: 0.2422 },
                        { name: '大寒', longitude: 300, baseDay: 20, coefficient: 0.2419 },
                        { name: '立春', longitude: 315, baseDay: 4, coefficient: 0.2422 },
                        { name: '雨水', longitude: 330, baseDay: 19, coefficient: 0.2422 },
                        { name: '惊蛰', longitude: 345, baseDay: 6, coefficient: 0.2422 },
                        { name: '春分', longitude: 0, baseDay: 21, coefficient: 0.2422 },
                        { name: '清明', longitude: 15, baseDay: 5, coefficient: 0.2422 },
                        { name: '谷雨', longitude: 30, baseDay: 20, coefficient: 0.2422 },
                        { name: '立夏', longitude: 45, baseDay: 6, coefficient: 0.2422 },
                        { name: '小满', longitude: 60, baseDay: 21, coefficient: 0.2422 },
                        { name: '芒种', longitude: 75, baseDay: 6, coefficient: 0.2422 },
                        { name: '夏至', longitude: 90, baseDay: 21, coefficient: 0.2422 },
                        { name: '小暑', longitude: 105, baseDay: 7, coefficient: 0.2422 },
                        { name: '大暑', longitude: 120, baseDay: 23, coefficient: 0.2422 },
                        { name: '立秋', longitude: 135, baseDay: 8, coefficient: 0.2422 },
                        { name: '处暑', longitude: 150, baseDay: 23, coefficient: 0.2422 },
                        { name: '白露', longitude: 165, baseDay: 8, coefficient: 0.2422 },
                        { name: '秋分', longitude: 180, baseDay: 23, coefficient: 0.2422 },
                        { name: '寒露', longitude: 195, baseDay: 8, coefficient: 0.2422 },
                        { name: '霜降', longitude: 210, baseDay: 24, coefficient: 0.2422 },
                        { name: '立冬', longitude: 225, baseDay: 8, coefficient: 0.2422 },
                        { name: '小雪', longitude: 240, baseDay: 22, coefficient: 0.2422 },
                        { name: '大雪', longitude: 255, baseDay: 7, coefficient: 0.2422 },
                        { name: '冬至', longitude: 270, baseDay: 22, coefficient: 0.2422 }
                    ];

                    // 查找当前月份的节气
                    for (const term of solarTerms) {
                        const termMonth = Math.floor((term.longitude % 360) / 30) + 1;
                        if (this.normalizeMonth(termMonth) === month) {
                            // 使用天文学公式精确计算节气日期
                            const termDay = this.calculateSolarTermDay(year, term);
                            
                            if (day === termDay) {
                                return term.name;
                            }
                        }
                    }
                    
                    return null;
                    
                } catch (error) {
                    console.error('节气计算错误:', error);
                    return null;
                }
            }

            // 精确计算节气日期的天文算法
            calculateSolarTermDay(year, termData) {
                // 基础计算：使用寿星万年历算法
                const centuryValue = Math.floor(year / 100);
                const yearInCentury = year % 100;
                
                // 计算基础日期
                let termDay = Math.floor(yearInCentury * termData.coefficient + termData.baseDay - centuryValue * 0.01);
                
                // 长期修正（考虑地球轨道变化）
                const baseYear = 2000;
                const yearOffset = year - baseYear;
                
                // 每400年的岁差修正
                const precessionCorrection = Math.floor(yearOffset / 400) * 0.0025;
                
                // 每4年的闰年修正
                const leapCorrection = Math.floor(yearOffset / 4) * 0.0006;
                
                // 每100年的世纪修正
                const centuryCorrection = Math.floor(yearOffset / 100) * 0.0078;
                
                // 应用所有修正
                termDay += precessionCorrection + leapCorrection - centuryCorrection;
                
                // 特殊节气的精确修正
                if (termData.name === '芒种') {
                    termDay = this.adjustMangzhong(year, termDay);
                } else if (termData.name === '夏至') {
                    termDay = this.adjustXiazhi(year, termDay);
                }
                
                return Math.round(termDay);
            }

            // 芒种节气精确修正
            adjustMangzhong(year, baseDay) {
                // 基于天文观测的精确数据
                if (year === 2025) return 5;
                if (year >= 2020 && year <= 2030) return Math.round(baseDay - 1);
                return Math.round(baseDay);
            }

            // 夏至节气精确修正
            adjustXiazhi(year, baseDay) {
                // 基于天文观测的精确数据
                if (year === 2025) return 21;
                if (year >= 2020 && year <= 2030) return Math.round(baseDay);
                return Math.round(baseDay);
            }

            // 标准化月份（处理跨月情况）
            normalizeMonth(month) {
                if (month <= 0) return month + 12;
                if (month > 12) return month - 12;
                return month;
            }
        }

        // 通用节假日数据类 - 支持任意年份
        class HolidayData {
            constructor() {
                // 固定日期的节假日
                this.fixedHolidays = {
                    "01-01": "元旦",
                    "05-01": "劳动节",
                    "06-01": "儿童节", 
                    "10-01": "国庆节"
                };
            }

            // 获取农历节假日的阳历日期（基于当年的农历计算）
            getLunarHolidayDate(year, lunarMonth, lunarDay) {
                // 这里应该实现农历转阳历的计算
                // 为了简化，先返回一些常见的农历节日的大概日期
                const lunarHolidays = {
                    "1-1": this.estimateSpringFestival(year),   // 春节
                    "5-5": this.estimateDragonBoat(year),       // 端午节  
                    "8-15": this.estimateMidAutumn(year),       // 中秋节
                    "12-30": this.estimateNewYearEve(year)      // 除夕
                };
                
                const key = `${lunarMonth}-${lunarDay}`;
                return lunarHolidays[key];
            }

            // 估算春节日期（通常在1月21日-2月20日之间）
            estimateSpringFestival(year) {
                // 简化算法：基于19年的农历周期
                const baseYear = 2000;
                const baseDate = new Date(2000, 1, 5); // 2000年春节是2月5日
                const cycle = (year - baseYear) % 19;
                
                // 每19年农历大约提前7天
                const offset = Math.floor(cycle * 365.25 / 19) - Math.floor(cycle * 7);
                const springDate = new Date(baseDate);
                springDate.setFullYear(year);
                springDate.setDate(springDate.getDate() + offset);
                
                return springDate;
            }

            // 估算端午节日期
            estimateDragonBoat(year) {
                const spring = this.estimateSpringFestival(year);
                const dragonBoat = new Date(spring);
                dragonBoat.setDate(spring.getDate() + 103); // 春节后约103天
                return dragonBoat;
            }

            // 估算中秋节日期  
            estimateMidAutumn(year) {
                const spring = this.estimateSpringFestival(year);
                const midAutumn = new Date(spring);
                midAutumn.setDate(spring.getDate() + 237); // 春节后约237天
                return midAutumn;
            }

            // 估算除夕日期
            estimateNewYearEve(year) {
                const nextSpring = this.estimateSpringFestival(year + 1);
                const newYearEve = new Date(nextSpring);
                newYearEve.setDate(nextSpring.getDate() - 1);
                return newYearEve;
            }

            // 获取指定日期的节假日名称
            getHoliday(year, month, day) {
                const key = `${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
                
                // 检查固定节假日
                if (this.fixedHolidays[key]) {
                    return this.fixedHolidays[key];
                }

                // 检查农历节假日
                const currentDate = new Date(year, month - 1, day);
                
                // 春节（通常有7天假期）
                const spring = this.estimateSpringFestival(year);
                if (this.isDateInRange(currentDate, spring, 7)) {
                    return "春节";
                }

                // 国庆节（通常有7天假期）
                const nationalDay = new Date(year, 9, 1); // 10月1日
                if (this.isDateInRange(currentDate, nationalDay, 7)) {
                    return "国庆节";
                }

                // 劳动节（通常有5天假期）  
                const laborDay = new Date(year, 4, 1); // 5月1日
                if (this.isDateInRange(currentDate, laborDay, 5)) {
                    return "劳动节";
                }

                // 端午节
                const dragonBoat = this.estimateDragonBoat(year);
                if (this.isSameDate(currentDate, dragonBoat)) {
                    return "端午节";
                }

                // 中秋节
                const midAutumn = this.estimateMidAutumn(year);
                if (this.isSameDate(currentDate, midAutumn)) {
                    return "中秋节";
                }

                // 清明节（4月4日或5日）
                if (month === 4 && (day === 4 || day === 5)) {
                    return "清明节";
                }

                return null;
            }

            // 检查调休工作日（这个需要每年手动更新）
            isWorkDay(year, month, day) {
                // 这里可以添加特定年份的调休工作日
                // 由于调休安排每年不同，建议从数据库或配置文件读取
                return false;
            }

            // 辅助方法：检查日期是否在指定范围内
            isDateInRange(targetDate, startDate, days) {
                const endDate = new Date(startDate);
                endDate.setDate(startDate.getDate() + days - 1);
                return targetDate >= startDate && targetDate <= endDate;
            }

            // 辅助方法：检查是否是同一天
            isSameDate(date1, date2) {
                return date1.getFullYear() === date2.getFullYear() &&
                       date1.getMonth() === date2.getMonth() &&
                       date1.getDate() === date2.getDate();
            }
        }

        // 日历控制器
        class CalendarController {
            constructor() {
                this.lunar = new LunarCalendar();
                this.holidayData = new HolidayData();
                this.currentDate = new Date();
                this.viewDate = new Date();
                this.holidaySettings = {};

                this.init();
            }

            init() {
                console.log('初始化日历控制器...');
                this.bindEvents();
                this.render(); // 先渲染日历
                this.loadHolidayData(); // 再加载数据并重新渲染
                console.log('日历控制器初始化完成');
            }

            bindEvents() {
                document.getElementById('prevMonth').addEventListener('click', () => {
                    this.viewDate.setMonth(this.viewDate.getMonth() - 1);
                    this.loadHolidayData(); // 切换月份时重新加载数据
                });

                document.getElementById('nextMonth').addEventListener('click', () => {
                    this.viewDate.setMonth(this.viewDate.getMonth() + 1);
                    this.loadHolidayData(); // 切换月份时重新加载数据
                });

                document.getElementById('today').addEventListener('click', () => {
                    this.viewDate = new Date();
                    this.loadHolidayData(); // 回到今天时重新加载数据
                });

                document.getElementById('closeModal').addEventListener('click', () => {
                    this.hideModal();
                });

                document.getElementById('cancelBtn').addEventListener('click', () => {
                    this.hideModal();
                });

                document.getElementById('confirmBtn').addEventListener('click', () => {
                    this.saveHolidaySetting();
                });

                // 弹窗外部点击事件已移到全局处理，避免重复绑定

                // 点击其他地方隐藏右键菜单（移到全局处理，避免重复绑定）
                // 这部分逻辑已移到DOMContentLoaded中统一处理
            }

            render() {
                this.renderHeader();
                this.renderCalendar();
            }

            renderHeader() {
                const year = this.viewDate.getFullYear();
                const month = this.viewDate.getMonth() + 1;
                document.getElementById('calendarTitle').textContent = `${year} 年 ${month} 月`;
            }

            renderCalendar() {
                console.log('开始渲染日历...');
                const year = this.viewDate.getFullYear();
                const month = this.viewDate.getMonth();
                
                console.log(`渲染日历: ${year}年${month + 1}月`);
                
                const firstDay = new Date(year, month, 1);
                const calendarBody = document.getElementById('calendarBody');
                
                if (!calendarBody) {
                    console.error('找不到 calendarBody 元素');
                    return;
                }
                
                calendarBody.innerHTML = '';

                const startDate = new Date(firstDay);
                const dayOfWeek = (firstDay.getDay() + 6) % 7;
                startDate.setDate(startDate.getDate() - dayOfWeek);

                console.log(`日历开始日期: ${startDate.toISOString().split('T')[0]}`);

                let dayCount = 0;
                for (let week = 0; week < 6; week++) {
                    for (let day = 0; day < 7; day++) {
                        const currentDate = new Date(startDate);
                        currentDate.setDate(startDate.getDate() + week * 7 + day);
                        
                        const dayElement = this.createDayElement(currentDate);
                        calendarBody.appendChild(dayElement);
                        dayCount++;
                    }
                }
                
                console.log(`日历渲染完成，共生成 ${dayCount} 个日期格子`);
            }

            createDayElement(date) {
                console.log(`创建日期元素: ${date.toISOString().split('T')[0]}`);
                
                try {
                    const dayElement = document.createElement('div');
                    dayElement.className = 'calendar-day';
                    
                    const year = date.getFullYear();
                    const month = date.getMonth() + 1;
                    const day = date.getDate();
                    const viewMonth = this.viewDate.getMonth() + 1;
                    
                    const isCurrentMonth = month === viewMonth;
                    const isToday = this.isSameDate(date, this.currentDate);
                    const isWeekend = date.getDay() === 0 || date.getDay() === 6;
                    
                    // 先尝试简单的农历计算，如果失败就用默认值
                    let lunarInfo;
                    try {
                        lunarInfo = this.lunar.solar2lunar(date);
                        console.log(`农历计算成功: ${date.toISOString().split('T')[0]} -> ${lunarInfo.dateStr}`);
                    } catch (lunarError) {
                        console.error('农历计算失败:', lunarError);
                        lunarInfo = {
                            dayStr: '初一',
                            monthStr: '正月',
                            dateStr: '正月初一'
                        };
                    }
                    
                    let solarTerm = null;
                    try {
                        solarTerm = this.lunar.getSolarTerm(date);
                    } catch (termError) {
                        console.error('节气计算失败:', termError);
                    }
                    
                    let holiday = null;
                    try {
                        holiday = this.holidayData.getHoliday(year, month, day);
                    } catch (holidayError) {
                        console.error('节假日计算失败:', holidayError);
                    }
                    
                    const isWorkDay = false; // 简化处理
                    
                    if (!isCurrentMonth) dayElement.classList.add('other-month');
                    if (isToday) dayElement.classList.add('today');
                    if (isWeekend) dayElement.classList.add('weekend');
                    if (holiday) dayElement.classList.add('holiday');

                    const dayNumber = document.createElement('div');
                    dayNumber.className = 'day-number';
                    dayNumber.textContent = day;

                    const lunarDate = document.createElement('div');
                    lunarDate.className = 'lunar-date';
                    lunarDate.textContent = lunarInfo.dayStr === '初一' ? lunarInfo.monthStr : lunarInfo.dayStr;

                    dayElement.appendChild(dayNumber);
                    dayElement.appendChild(lunarDate);

                    if (solarTerm) {
                        const holidayName = document.createElement('div');
                        holidayName.className = 'holiday-name';
                        holidayName.textContent = solarTerm;
                        dayElement.appendChild(holidayName);
                    } else if (holiday) {
                        const holidayName = document.createElement('div');
                        holidayName.className = 'holiday-name';
                        holidayName.textContent = holiday;
                        dayElement.appendChild(holidayName);
                    }

                    const dateKey = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
                    
                    // 只有数据库中有明确设置时才显示按钮
                    if (this.holidaySettings[dateKey] !== undefined) {
                        const holidayType = this.holidaySettings[dateKey];
                        const dataSource = '数据库';
                        
                        // 为日期格子添加背景样式类
                        if (holidayType === 0) {
                            dayElement.classList.add('has-holiday'); // 假日背景
                        } else {
                            dayElement.classList.add('has-work-day'); // 工作日背景
                        }
                        
                        // 创建按钮
                        const workBtn = document.createElement('button');
                        workBtn.className = holidayType === 0 ? 'work-btn holiday' : 'work-btn work-day';
                        
                        workBtn.textContent = holidayType === 0 ? '假' : '班';
                        workBtn.title = `${dateKey} - ${dataSource}设置: ${holidayType === 0 ? '假日' : '工作日'}`;
                        
                        workBtn.addEventListener('click', (e) => {
                            e.stopPropagation();
                            this.showModal(date, holidayType);
                        });

                        dayElement.appendChild(workBtn);
                    }

                    // 添加右键菜单事件
                    dayElement.addEventListener('contextmenu', (e) => {
                        e.preventDefault();
                        this.showContextMenu(e, date);
                    });
                    
                    console.log(`日期元素创建完成: ${dateKey}`);
                    return dayElement;
                    
                } catch (error) {
                    console.error(`创建日期元素失败 ${date.toISOString().split('T')[0]}:`, error);
                    
                    // 创建一个简单的fallback元素，不显示按钮
                    const fallbackElement = document.createElement('div');
                    fallbackElement.className = 'calendar-day';
                    fallbackElement.innerHTML = `
                        <div class="day-number">${date.getDate()}</div>
                        <div class="lunar-date">未知</div>
                    `;
                    return fallbackElement;
                }
            }

            showModal(date, currentType) {
                this.selectedDate = date;
                const year = date.getFullYear();
                const month = date.getMonth() + 1;
                const day = date.getDate();
                
                document.getElementById('modalDate').value = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
                document.getElementById('modalType').value = currentType;
                document.getElementById('holidayModal').style.display = 'block';
            }

            hideModal() {
                document.getElementById('holidayModal').style.display = 'none';
            }

            saveHolidaySetting() {
                const date = this.selectedDate;
                const type = parseInt(document.getElementById('modalType').value);
                const year = date.getFullYear();
                const month = date.getMonth() + 1;
                const day = date.getDate();
                const dateKey = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
                
                // 准备JSON数据（匹配控制器期望的格式）
                const requestData = {
                    HolidayDate: dateKey + 'T00:00:00', // 确保日期格式正确
                    HolidayType: type
                };
                
                // 发送到服务器保存
                fetch('/ProductionSystem/ShiftManagement/HolidaySetting/SaveHolidaySetting', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify(requestData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        // 更新本地数据
                        this.holidaySettings[dateKey] = type;
                        this.hideModal();
                        this.render();
                        console.log('保存节假日设置成功:', dateKey, type === 0 ? '假' : '班');
                        
                        // 显示成功提示（只显示一次）
                        alert('保存成功');
                    } else {
                        alert('保存失败：' + (data.message || '未知错误'));
                    }
                })
                .catch(error => {
                    console.error('保存节假日设置失败:', error);
                    alert('保存失败，请重试。错误信息：' + error.message);
                });
            }

            isSameDate(date1, date2) {
                return date1.getFullYear() === date2.getFullYear() &&
                       date1.getMonth() === date2.getMonth() &&
                       date1.getDate() === date2.getDate();
            }

            // 显示右键菜单
            showContextMenu(e, date) {
                this.selectedDate = date;
                const contextMenu = document.getElementById('contextMenu');
                contextMenu.style.display = 'block';
                contextMenu.style.left = e.pageX + 'px';
                contextMenu.style.top = e.pageY + 'px';
                
                // 根据本地数据快速判断菜单项显示
                const dateKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
                const hasData = this.holidaySettings[dateKey] !== undefined;
                
                const addItem = document.getElementById('addHoliday');
                const editItem = document.getElementById('editHoliday');
                const deleteItem = document.getElementById('deleteHoliday');
                
                if (hasData) {
                    // 有数据，隐藏添加选项，显示修改和删除选项
                    addItem.style.display = 'none';
                    editItem.style.display = 'block';
                    deleteItem.style.display = 'block';
                } else {
                    // 无数据，显示添加选项，隐藏修改和删除选项
                    addItem.style.display = 'block';
                    editItem.style.display = 'none';
                    deleteItem.style.display = 'none';
                }
            }

            // 隐藏右键菜单
            hideContextMenu() {
                document.getElementById('contextMenu').style.display = 'none';
            }



            // 打开添加/修改弹窗
            openAddOrEditModal(date, isEdit = false) {
                const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
                
                if (isEdit) {
                    // 获取现有数据并显示修改弹窗
                    fetch(`/ProductionSystem/ShiftManagement/HolidaySetting/GetHolidayByDate?date=${dateStr}`, {
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error(`HTTP error! status: ${response.status}`);
                            }
                            return response.json();
                        })
                        .then(data => {
                            if (data.success && data.data) {
                                this.showHolidayModal(date, data.data.holidayType);
                            } else {
                                this.showHolidayModal(date, 0); // 默认为假
                            }
                        })
                        .catch(error => {
                            console.error('获取节假日数据失败:', error);
                            this.showHolidayModal(date, 0); // 默认为假
                        });
                } else {
                    // 显示添加弹窗
                    this.showHolidayModal(date, 0); // 默认为假
                }
                
                this.hideContextMenu();
            }

            // 显示节假日设置弹窗
            showHolidayModal(date, currentType = 0) {
                this.selectedDate = date;
                const year = date.getFullYear();
                const month = date.getMonth() + 1;
                const day = date.getDate();
                
                document.getElementById('modalDate').value = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
                document.getElementById('modalType').value = currentType;
                document.getElementById('holidayModal').style.display = 'block';
            }

            // 删除指定日期的节假日设置
            deleteHolidayByDate(date) {
                const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
                
                if (confirm('确定要删除这个节假日设置吗？')) {
                    const formData = new FormData();
                    formData.append('date', dateStr);
                    
                    fetch('/ProductionSystem/ShiftManagement/HolidaySetting/DeleteHolidaySetting', {
                        method: 'POST',
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        body: formData
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.success) {
                            alert('删除成功');
                            this.loadHolidayData(); // 重新加载数据
                        } else {
                            alert('删除失败：' + (data.message || '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error('删除失败:', error);
                        alert('删除失败，请重试。错误信息：' + error.message);
                    });
                }
                
                this.hideContextMenu();
            }

            // 加载数据库中的节假日设置
            loadHolidayData() {
                const year = this.viewDate.getFullYear();
                const month = this.viewDate.getMonth() + 1;
                
                console.log(`正在加载 ${year}年${month}月 的节假日数据...`);
                
                // 使用fetch API获取数据
                fetch(`/ProductionSystem/ShiftManagement/HolidaySetting/GetHolidaySettings?year=${year}&month=${month}`, {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        console.log('节假日数据加载结果:', data);
                        if (data.success && data.data) {
                            this.holidaySettings = {};
                            data.data.forEach(holiday => {
                                const date = new Date(holiday.holidayDate);
                                const dateKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
                                this.holidaySettings[dateKey] = holiday.holidayType;
                                console.log(`数据库数据: ${dateKey} = ${holiday.holidayType === 0 ? '假' : '班'}`);
                            });
                        } else {
                            this.holidaySettings = {};
                            console.log('本月无节假日设置数据');
                        }
                        this.render(); // 重新渲染日历
                    })
                    .catch(error => {
                        console.error('加载节假日数据失败:', error);
                        this.holidaySettings = {};
                        this.render(); // 即使失败也要渲染日历
                    });
            }
        }

        // 全局变量存储日历实例
        let calendarInstance = null;

        // 右键菜单处理函数
        function handleAddHoliday() {
            if (calendarInstance && calendarInstance.selectedDate) {
                calendarInstance.openAddOrEditModal(calendarInstance.selectedDate, false);
            }
        }

        function handleEditHoliday() {
            if (calendarInstance && calendarInstance.selectedDate) {
                calendarInstance.openAddOrEditModal(calendarInstance.selectedDate, true);
            }
        }

        function handleDeleteHoliday() {
            if (calendarInstance && calendarInstance.selectedDate) {
                calendarInstance.deleteHolidayByDate(calendarInstance.selectedDate);
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            console.log('页面DOM加载完成，开始初始化日历...');
            try {
                calendarInstance = new CalendarController();
                console.log('日历控制器创建成功');
                
                // 全局事件绑定（只绑定一次，避免重复）
                
                // 点击页面其他地方隐藏右键菜单
                document.addEventListener('click', function(e) {
                    if (!e.target.closest('#contextMenu')) {
                        document.getElementById('contextMenu').style.display = 'none';
                    }
                });
                
                // 点击弹窗外部区域隐藏弹窗
                document.getElementById('holidayModal').addEventListener('click', function(e) {
                    if (e.target === this) {
                        calendarInstance.hideModal();
                    }
                });
                
            } catch (error) {
                console.error('日历初始化失败:', error);
            }
        });
    </script>

    <!-- 右键菜单 -->
    <div id="contextMenu" class="context-menu" style="display: none;">
        <ul>
            <li id="addHoliday" onclick="handleAddHoliday()">添加节假日</li>
            <li id="editHoliday" onclick="handleEditHoliday()">修改节假日</li>
            <li id="deleteHoliday" onclick="handleDeleteHoliday()">删除节假日</li>
        </ul>
    </div>

    <style>
        .context-menu {
            position: absolute;
            background: white;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            z-index: 1000;
        }

        .context-menu ul {
            list-style: none;
            margin: 0;
            padding: 0;
        }

        .context-menu li {
            padding: 8px 16px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }

        .context-menu li:last-child {
            border-bottom: none;
        }

        .context-menu li:hover {
            background-color: #f5f5f5;
        }
    </style>
</body>
</html> 